import { defineStore } from 'pinia'
import { ref } from 'vue'
import axios from 'axios'

export interface Role {
  id: number
  name: string
  code: string
  description?: string
  is_active: boolean
  created_at: string
  updated_at: string
}

export interface CreateRoleForm {
  name: string
  code: string
  description?: string
  is_active: boolean
}

export interface UpdateRoleForm {
  id: number
  name?: string
  code?: string
  description?: string
  is_active?: boolean
}

export const useRoleStore = defineStore('role', () => {
  const roles = ref<Role[]>([])
  const loading = ref(false)
  const error = ref<string | null>(null)
  const total = ref(0)

  async function fetchRoles(params: {
    page?: number
    pageSize?: number
    search?: string
  } = {}) {
    loading.value = true
    error.value = null
    
    try {
      const response = await axios.get('/api/roles/', { params })
      roles.value = response.data.roles
      total.value = response.data.total
      return { success: true }
    } catch (err: any) {
      error.value = err.response?.data?.message || '获取角色列表失败'
      return { success: false, error: error.value }
    } finally {
      loading.value = false
    }
  }

  async function createRole(roleData: CreateRoleForm) {
    loading.value = true
    error.value = null
    
    try {
      const response = await axios.post('/api/roles/', roleData)
      roles.value.push(response.data)
      return { success: true, role: response.data }
    } catch (err: any) {
      error.value = err.response?.data?.message || '创建角色失败'
      return { success: false, error: error.value }
    } finally {
      loading.value = false
    }
  }

  async function updateRole(roleData: UpdateRoleForm) {
    loading.value = true
    error.value = null
    
    try {
      const response = await axios.put(`/api/roles/${roleData.id}`, roleData)
      const index = roles.value.findIndex(r => r.id === roleData.id)
      if (index !== -1) {
        roles.value[index] = response.data
      }
      return { success: true, role: response.data }
    } catch (err: any) {
      error.value = err.response?.data?.message || '更新角色失败'
      return { success: false, error: error.value }
    } finally {
      loading.value = false
    }
  }

  async function deleteRole(roleId: number) {
    loading.value = true
    error.value = null
    
    try {
      await axios.delete(`/api/roles/${roleId}`)
      roles.value = roles.value.filter(r => r.id !== roleId)
      return { success: true }
    } catch (err: any) {
      error.value = err.response?.data?.message || '删除角色失败'
      return { success: false, error: error.value }
    } finally {
      loading.value = false
    }
  }

  async function getRolePermissions(roleId: number) {
    loading.value = true
    error.value = null
    
    try {
      const response = await axios.get(`/api/roles/${roleId}/permissions`)
      return { success: true, permissions: response.data.permissions }
    } catch (err: any) {
      error.value = err.response?.data?.message || '获取角色权限失败'
      return { success: false, error: error.value }
    } finally {
      loading.value = false
    }
  }

  async function assignRolePermissions(roleId: number, permissionIds: number[]) {
    loading.value = true
    error.value = null
    
    try {
      const response = await axios.post(`/api/roles/${roleId}/permissions`, {
        permission_ids: permissionIds
      })
      return { success: true, message: response.data.message }
    } catch (err: any) {
      error.value = err.response?.data?.message || '分配权限失败'
      return { success: false, error: error.value }
    } finally {
      loading.value = false
    }
  }

  async function getRoleUsers(roleId: number) {
    loading.value = true
    error.value = null
    
    try {
      const response = await axios.get(`/api/roles/${roleId}/users`)
      return { success: true, users: response.data.users }
    } catch (err: any) {
      error.value = err.response?.data?.message || '获取角色用户失败'
      return { success: false, error: error.value }
    } finally {
      loading.value = false
    }
  }

  return {
    roles,
    loading,
    error,
    total,
    fetchRoles,
    createRole,
    updateRole,
    deleteRole,
    getRolePermissions,
    assignRolePermissions,
    getRoleUsers
  }
})
